package sing.myapp.net.interceptor

import android.os.Build
import com.alibaba.fastjson.JSONObject
import sing.core.util.EncryptUtil
import okhttp3.*
import sing.core.BuildConfig
import sing.core.Global
import sing.core.util.AppUtil
import sing.core.util.MMkvUtil
import java.util.*


/**
 * 自定义头部参数拦截器，传入heads
 */
class MyParamsInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val orgRequest = chain.request()
        val body = orgRequest.body()

        if (body != null) {
            var newBody: RequestBody? = null
            if (body is FormBody) {
                newBody = addParamsToFormBody(body)
            } else if (body is MultipartBody) {
                newBody = addParamsToMultipartBody(body)
//                newBody = body
            } else {
//                newBody = addParamsToFormBody(null)
                newBody = body
            }
            if (null != newBody) {
                val url = StringBuffer()
                url.append(orgRequest.url())

                url.append("?os=2")
                url.append("&network=${MMkvUtil().network}")
                url.append("&model=${AppUtil.getDeviceBrand()}")
                url.append("&version=${AppUtil.versionName}")
                val imei = MMkvUtil().imei
                if (imei.isNotEmpty()){
                    url.append("&device_id=$imei")
                }else{
                    val oaid = MMkvUtil().oaid
                    url.append("&device_id=$oaid")
                }
                val channelId = MMkvUtil().channelId
                if ("$channelId".isNotEmpty()){
                    url.append("&channel_id=$channelId")
                }

                url.append("&device=Android")
                //打印参数
                val newRequest = orgRequest.newBuilder()
                    .url(url.toString())
                    .method(orgRequest.method(), newBody)
                    .build()
                return chain.proceed(newRequest)
            }
        }

        return chain.proceed(orgRequest)
    }


    /**
     * 为MultipartBody类型请求体添加参数
     *
     * @param body
     * @param paramsBuilder
     * @return
     */
    private fun addParamsToMultipartBody(body: MultipartBody): MultipartBody? {
        val builder = MultipartBody.Builder()
        builder.setType(MultipartBody.FORM)
//        builder.addFormDataPart("appcode", appcode)

        //添加原请求体
        for (i in 0 until body.size()) {
            builder.addPart(body.part(i))
        }
        return builder.build()
    }

    /**
     * 为FormBody类型请求体添加参数
     *
     * @param body
     * @return
     */
    private fun addParamsToFormBody(body: FormBody?): FormBody? {
        val builder = FormBody.Builder()

        val map = getParams()
        for (key in map.keys) {
            builder.add(key, "${map[key]}")
        }

        if (body != null) {
            //添加原请求体
            for (i in 0 until body.size()) {
                builder.addEncoded(body.encodedName(i), body.encodedValue(i))
            }
        }

        return builder.build()
    }

    fun getParams(): Map<String, String> {
        val p = HashMap<String, String>()
//        p["os"] = "android"
//        p["channelId"] = Global.channel
//        val token = MMkvUtil().token
//        if (token.isNotEmpty()) {
//            p["loginToken"] = token
//        }
////        val id = MMkvUtil().userId
////        if (id.isNotEmpty()) {
////            p["id"] = id
////        }
//
//        p["ip"] = MMkvUtil().ip
//        p["mark"] = BuildConfig.MARK
//        p["imei_md5"] = ""
//        p["ua"] = Build.MODEL
//        p["oaid"] = oaid
//        p["oaid_md5"] = EncryptUtil.getMD5(oaid)
//        p["imei"] = ""
        
//        p["os"] = "2" // 操作系统类型 默认1=iOS；2=安卓
//        p["network"] = MMkvUtil().network // 网络
//        p["model"] = AppUtil.getDeviceBrand() // 设备型号 OnePlus Xiaomi
//        p["version"] = AppUtil.versionName // app版本 1.1.1

//        val imei = MMkvUtil().imei
//        if (imei.isNotEmpty()){
//            p["device_id"] = imei // 设备唯一标识
//        }else{
//            val oaid = MMkvUtil().oaid
//            p["device_id"] = oaid // 设备唯一标识
//        }

        return p
    }
}